<?php
/**
 * @action  客户管理的控制器
 * @authors guo (guomingliangphp@163.com)
 * @date    2014-01-11 09:54:52
 * @version $Id$
 */
class UserAction extends CommonAction{
   
    //列出指定代理商下面的所有用户或者是即将到期的用户(包括对用户的查询)
    public function userlist()
    {
        $agentId=$_SESSION["agent"]["id"];
        import("ORG.Util.Page");
        $userModel = D("User");
        $pagenumber =7;

        if(I('get.status')=='expired'){
            $condition["Usermoney"]=array('lt',1000);
            $this->status="expired";
        }
        if(I('get.otn')){
            $otn=I('get.otn');
            $content=I('get.content');
            if(!$content){
                $this->error("请输入查询内容");
            }
            switch($otn){
                case userName:
                    $condition['Username']=array("like","%$content%");
                    break;
                case realName:
                    $condition['Realname']=array("like","%$content%");
                    break;
                case company:
                    $condition['Company']=array("like","%$content%");
                    break;
            }
        }
        $condition["ProxyId"]=$agentId;
        $totalnum = $userModel->where($condition)->count();
//查询出用户的站点数量
        $siteModel=M("website");
        $userNames=R('Agent/userlist');
        $sql="select count(Id) sitenum,Username from yst_website where Username in ($userNames) group by Username";
        $countlist=$siteModel->query($sql);
        $countsite=array();
        foreach($countlist as $key=>$val){
            $countsite["$val[Username]"]=$val['sitenum'];
        }
//查询出用户的关键词数量
        $keywordModel=M("keyword");
        $sql="select count(id) keywordnum,Username from yst_keyword where Username in ($userNames) and enyinqing='baidu' group by Username";
        $keywordlist=$keywordModel->query($sql);
        $countkeyword=array();
        foreach($keywordlist as $key => $val){
            $countkeyword["$val[Username]"]=$val['keywordnum'];
        }
        $list =$userModel->where($condition)->page($_GET['p'])->limit($pagenumber)->order('id desc')->select();

        foreach($list as $k=>&$v){
            $v['sitenum']=$countsite[$v['Username']];
            if (!isset($v['sitenum']))
                $v['sitenum'] = 0;
        }
        foreach($list as $k=>&$v){
            $v['keywordnum']=$countkeyword[$v['Username']];
            if (!isset($v['keywordnum']))
                $v['keywordnum'] = 0;
        }

        $this->assign("list", $list);
        $page = new Page($totalnum, $pagenumber);
        $page->setConfig("prev", "上一页");
        $page->setConfig("next", "下一页");
        $page->setConfig("first", "首页");
        $page->setConfig("last", "末页");
        $page->setConfig("theme","<span class=pageinfo> <u></u>当前%nowPage%/%totalPage%页</span>
                                     %first% %upPage%   %linkPage%  %downPage% %end%");
        $pageshow = $page->show();
        $this->assign("pageshow", $pageshow);
        $this->display();
    }

    //代理商下的客户统计概括
    public function userstatistics(){

        //统计代理商下的停用客户，即将到期的客户和客户总数
        $userInfo=R("Agent/user_info");
        $this->userInfo=$userInfo;

        //取得该代理商下的所有用户的用户名(是一个字符串)
        $userStr=R("Agent/userlist");
        $condition['Username']=array("exp","in($userStr)");

        //代理商下的用户的总站点数
         $websiteModel=M("website");
         $siteNum=$websiteModel->where($condition)->count();
         $this->siteNum=$siteNum;

       //代理商下的用户所有关键词的数量
        $condition['enyinqing']='baidu';
        $keywordModel=M("keyword");
        $keywordNum=$keywordModel->where($condition)->count();
        $this->keywordNum=$keywordNum;

        //代理商今年每月增加的客户数量
        $json_month=R('Agent/newnumbmonthly');
        $this->assign('json_month',$json_month);
        $this->display();

    }

    //客户充值操作
    public function userrecharge(){

        $names=R("Agent/userlist");
        $this->names=$names;

        if(I("get.userId")){
            $userId=I("get.userId");
            $userModel=M("user");
            $userList=$userModel->find($userId);
            $this->assign("userList",$userList);
            $this->assign("userId",$userId);
        }
        $this->display();
    }

    //客户充值的保存操作
    public function userrechargesave(){

       if(IS_POST){
           $condition['Username']=I("post.userName");
           $condition['ProxyId']=$_SESSION['agent']['id'];
           $addMoney=I("post.addMoney");
           $userModel=M("user");
           //创建充值记录的订单
           $userId=$userModel->where($condition)->field("Id")->find();
           $userId=$userId['Id'];
           $order=new OrderAction();
           $orderId=$order->orderaddsave($userId,$addMoney);
           if($orderId){
               $result=$userModel->where($condition)->setInc("Usermoney",$addMoney);
               if($result){
                   $res=$order->changestatus($orderId);
                   if(!$res){
                       $ajax['Msg']='充值成功，充值订单创建失败';
                       echo json_encode($ajax);
                       die();
                   }
                   $ajax['status']='true';
                   $ajax['Msg']='充值成功';
                   $ajax['url']="/Order/ordercontent/orderId/$orderId";
                   echo json_encode($ajax);
                   die();
               }else{
                   $ajax['Msg']='充值失败';
                   echo json_encode($ajax);
                   die();
               }
           }else{
               $ajax['Msg']='充值订单创建失败';
               echo json_encode($ajax);
               die();
           }
       }
    }
    //异步获取客户的信息
    public function userinfo(){
        if(I("post.userName")){
            $username=I("post.userName");
            $condition['Username']=I("post.userName");
            $condition['ProxyId']=$_SESSION['agent']['id'];
            $userModel=M("user");
            $userList=$userModel->where($condition)->field("Realname,Company,Usermoney")->find();
            if($userList){
                $userList["status"]="true";
                $ajax=json_encode($userList);
                echo $ajax;
                die();
            }else{
                $ajax['errMsg']="用户不存在";
                $ajax["status"]="false";
                echo json_encode($ajax);
                die();
            }
        }
    }

    //代理商添加精准词客户
    public function useradd(){

        $hzstr = $this->getjson();
        $this->houzhui = $hzstr; //---------------------后缀词类型数据 json
        $diqustr = $this->diqudata();
        $this->diqustr = $diqustr;//--------------------地区数据  json
        $agentId=$_SESSION['agent']['id'];
        $acounttypeModel=M("acounttype");
        $condition['proxyid']=array(array('eq',0),array('eq',$agentId),'or');
        $kaihutype=$acounttypeModel->where($condition)->select();
        $this->assign('acounttype',$kaihutype);
        $this->display();
    }

    //代理商添加主词客户
    public function useraddkeyword(){

        $agentId=$_SESSION['agent']['id'];
        $acounttypeModel=M("acounttype");
        $condition['proxyid']=array(array('eq',0),array('eq',$agentId),'or');
        $kaihutype=$acounttypeModel->where($condition)->select();
        $this->assign('acounttype',$kaihutype);
        $this->display();
    }
//选择开户类型后返回扣费金额
public function userchargemoney(){
   $id=I("post.id");
   if(!$id){
       $ajax['Msg']="请选择开户类型";
       $ajax['status']="false";
       echo  json_encode($ajax);
       die();
   }
    $acounttypeModel=M("acounttype");
    $acountmoney=$acounttypeModel->field("money")->find($id);
    $ajax['money']=$acountmoney['money'];
    $ajax['status']="true";
    echo json_encode($ajax);
    die();
}

    //代理商添加客户的保存操作
    public function  useraddsave(){

         $user=D("user");
         $agentId=$_SESSION['agent']['id'];
         if(IS_POST){

             $safeCode=I("post.safecode");
             $safeCode=md5($safeCode);
             $condition['id']=$agentId;
             $condition['safecode']=$safeCode;
             $result=M("proxy")->where($condition)->find();
             if(!$result){
                 $ajax['Msg']="支付安全码不正确";
                 $ajax['status']='false';
                 echo json_encode($ajax);
                 die();
             }
             unset($result);
             unset($condition);

             $data['Username']=I("post.userName");
             $result=$user->where("Username='".$data['Username']."'")->find();
             if($result){
                 $ajax['Msg']="用户名已经存在";
                 $ajax['status']='false';
                 echo json_encode($ajax);
                 die();
             }
             unset($result);

             $data['Password']=I("post.password");
             $data['Password']=md5($data['Password']);

             $data['Realname']=I("post.realName");
             $data['Company']=I("post.company");
             $data['Mobile']=I("post.mobile");
             $data['Email']=I("post.email");
             $data['Type']=I("post.otn");
             $acountModel=M("acounttype");
             $money=$acountModel->field("money")->find($data['Type']);
             $money=$money['money'];
             $chongzhi=I("post.money");
             $data['Contractmoney']=$chongzhi;
             $data['Active']=1;
             $data['Regtime']=date('Y-m-d H:i:s');
             $data['ProxyId']=$agentId;
             $userType=I("post.userType");
             if($userType=='jingzhun'){
                 $data['Usertype']=1;
                 $data['Usermoney']=$chongzhi-$money;
                 if($data['Usermoney']<0){
                     $ajax['status']="false";
                     $ajax['Msg']="充值金额不足";
                     echo json_encode($ajax);
                     die();
                 }
             }
             if($userType=='common'){
                 $data['Usertype']=0;
                 $data['Usermoney']=$chongzhi-$money;
                 if($data['Usermoney']<0){
                     $ajax['status']="false";
                     $ajax['Msg']="充值金额不足";
                     echo json_encode($ajax);
                     die();
                 }
             }

             $result=$user->add($data);
             if($result){
                 $ajax['status']="true";
                 $ajax['next']="two";
                 echo json_encode($ajax);
             }
         }
    }

    //异步获取某一个用户下面的所有网站
    public function usersites(){

        $agentId=$_SESSION['agent']['id'];
        $user=M("user");
        if(IS_POST){
            $userName=I("post.userName");
            $condition['ProxyId']=$agentId;
            $condition['Username']=$userName;
            $result=$user->where($condition)->find();

           if(!$result){
                $ajax['status']="false";
                $ajax['Msg']="该用户不存在";
                echo json_encode($ajax);
                die();
            }
            unset($condition['ProxyId']);
            $website=M("website");
            $sitelist=$website->where($condition)->field("Id,Domain")->select();
            foreach($sitelist as $k=>$v){
                   $sites[$v['Id']]=$v['Domain'];
            }
            $sites['status']='true';
            $sites=json_encode($sites);
            echo $sites;
            die();

        }
    }
//显示某一个用户下面的所有网站

public  function usersite(){

    import("ORG.Util.Page");
    $agentId=$_SESSION['agent']['id'];
    $user=M("user");
    if(IS_GET){
        $userId=I("get.userId");
        $condition['ProxyId']=$agentId;
        $condition['Id']=$userId;
        $result=$user->where($condition)->find();
        if(!$result) $this->error("用户不存在");
        $this->assign("userInfo",$result);
        $webSite=M("website");
        unset($condition);
        $condition['Userid']=$userId;
        $pagenumber=8;
        $totalnum=$webSite->where($condition)->count();
        $list =$webSite->where($condition)->page($_GET['p'])->limit($pagenumber)->order('id desc')->select();
        //用户下的站点
        $webNames=$webSite->where("Userid=$userId")->field('Domain')->select();
        $webNams="";
        foreach($webNames as $k=>$v){
            $webNams.="'".$v['Domain']."',";
        }
        $webNams=substr($webNams,0,-1);
        $keyword=M("keyword");
        $sql="select count(id) keywordnum,Website from yst_keyword where Website in ($webNams) and enyinqing='baidu' group by Website";
        $keywordlist=$keyword->query($sql);

        $keylist=array();
        foreach($keywordlist as $k=>$v){
            $keylist[$v['Website']]=$v['keywordnum'];
        }
        foreach($list as $key=>&$val){
            $val['keywordnum']=$keylist[$val['Domain']];
            if (!isset($val['keywordnum']))
                $val['keywordnum'] = 0;

        }
        $this->assign("list", $list);
        $page = new Page($totalnum, $pagenumber);
        $page->setConfig("prev", "上一页");
        $page->setConfig("next", "下一页");
        $page->setConfig("first", "首页");
        $page->setConfig("last", "末页");
        $page->setConfig("theme","<span class=pageinfo> <u></u>当前%nowPage%/%totalPage%页</span>
                                     %first% %upPage%   %linkPage%  %downPage% %end%");
        $pageshow = $page->show();
        $this->assign("pageshow", $pageshow);
        $this->display();
    }
}
    //某个用户的详细信息
    public function userdetail(){

        $user=M("user");
        $agent=M("proxy");
        $agentId=$_SESSION['agent']['id'];
        $userId=I("get.userId");
        if(!$userId)  $this->error("请选择用户");
        $this->userId=$userId;
        $condition['ProxyId']=$agentId;
        $condition['Id']=$userId;
        $userInfo=$user->where($condition)->find();
        if(!$userInfo) $this->error("该用户不属于当前代理商");
        $userName=$user->where("Id=$userId")->getField("Username");
        $agentName=$agent->where("id=$agentId")->getField("username");
        $this->agentName=$agentName;
        $this->assign("userInfo",$userInfo);
        //获取用户的统计信息
        $money=$this->usertongji($userId);
        $this->assign('money',$money);
        //获取用户近30天的消费情况
        $chartdata=$this->userconsumption($userName);
        $category=$chartdata['category'];
        $showdatas=$chartdata['showdatas'];
        $this->assign('category',$category);
        $this->assign('showdatas',$showdatas);
        $this->display();
    }

   //某个特定用户的统计信息
    public  function usertongji($userId){

        if(!$userId) $this->error("没有获取到用户的信息");

        $agentId=$_SESSION['agent']['id'];
        $userName=M("user")->where("Id=$userId and ProxyId=$agentId")->getField("Username");
        if(!$userName) $this->error("该用户不属于当前代理商");

        //该客户的累计消费
        $consumptionModel=M("consumption");
        $condition['username']=$userName;
        $money['total']=$consumptionModel->where($condition)->sum('money');

        //该客户的平均消费
        $sql="select to_days(now())-min(to_days(addtime)) as days from yst_consumption where username='".$userName."'";
        $days=$consumptionModel->query($sql);
        $days=$days[0]['days'];
        $money['avg']=$money['total']/$days;
        $money['avg']=sprintf('%.1f',$money['avg']);

        //该用户本月的消费
        $sql = 'SELECT SUM(money) as monthmoney';
        $sql.= ' FROM yst_consumption ';
        $sql.= " WHERE username ='".$userName."'";
        $sql.= " AND DATE_FORMAT(addtime, '%Y%m' ) = DATE_FORMAT( CURDATE( ) , '%Y%m' )";
        $money['monthmoney']=$consumptionModel->query($sql);
        $money['month']=$money['monthmoney'][0]['monthmoney'];


        //该用户的昨日消费
        $sql = 'SELECT SUM(money) as yesterdaymoney';
        $sql.= ' FROM yst_consumption ';
        $sql.= " WHERE username ='".$userName."'";
        $sql.= ' AND TO_DAYS( NOW( ) ) - TO_DAYS(addtime) = 1';
        $money['yesterday']=$consumptionModel->query($sql);
        $money['yesterday']=$money['yesterday'][0]['yesterdaymoney'];

        //该用户上月的消费
        $sql = 'SELECT SUM(money) as lastmonth';
        $sql.= ' FROM yst_consumption ';
        $sql.= " WHERE username ='".$userName."'";
        $sql.= " AND DATE_FORMAT(addtime, '%Y-%m' ) = DATE_FORMAT(DATE_SUB(CURDATE(), INTERVAL 1 MONTH),'%Y-%m')";
        $money['lastmonth']=$consumptionModel->query($sql);
        $money['lastmonth']=$money['lastmonth'][0]['lastmonth'];

        //该客户的预计使用天数
        $userMoney=M("user")->where("Id=$userId")->getField("Usermoney");
        $money['usenum']=floor($userMoney/$money['avg']);

        //该客户的站点数量
        $money['sitenum']=M('website')->where("Userid=$userId")->count('Id');

        //该客户的关键词数量
        unset($condition);
        $condition['Username']=$userName;
        $condition['enyinqing']='baidu';
        $money['wordnum']=M('keyword')->where($condition)->count('id');
        return $money;
    }

    //某一用户近30天的消费情况
    public function userconsumption($userName){

        $agentId=$_SESSION['agent']['id'];
        if(!(M('user')->where("Username='".$userName."' and ProxyId='".$agentId."'")->find())) $this->error("该用户不存在");

        $sql = " SELECT sum(money) as tmoney ,DATE_FORMAT(addtime,'%d') as time";
        $sql .=" ,TO_DAYS(NOW())-to_days(addtime) as days,to_days(addtime) as dayparam ";
        $sql .= " from yst_consumption where username = '".$userName ."'group by TO_DAYS(addtime) order by addtime desc limit 0 ,30";

        $zdata = M('consumption')->query($sql);
        $category = "";
        $showdatas = "";
        $template = "{ y:%f,days:'%d' },";
        $showarray = array();
        foreach ($zdata as $k => $v) $showarray[$v["days"]] = $v;

        for ($i = 30; $i > 0; $i--)
        {
            $money = 0;
            $cutetime = time() - $i * 24 * 3600;
            $time = date("d", $cutetime);
            $days=0;
            $elemnet = $showarray[$i];
            if (!empty($elemnet))
            {
                $money = $elemnet["tmoney"];
                $days = $elemnet["dayparam"];
            }

            $category .= "'" . $time . "',";
            $showdatas .= sprintf($template, $money, $days);
        }

        $category=substr($category,0,-1);
        $showdatas=substr($showdatas,0,-1);

        $chartdata["category"]=$category;
        $chartdata["showdatas"]=$showdatas;
        return $chartdata;
    }

    //修改用户资料
    public function useredit(){
        $userId=I("get.userId");
        $agentId=$_SESSION['agent']['id'];
        if(!$userId) $this->error("选择用户失败");
        if(!(M('user')->where("Id='".$userId."' and ProxyId='".$agentId."'")->find())) $this->error("该用户不存在");
        $userInfo=M('user')->where("Id=$userId")->find();
        $this->assign("userInfo",$userInfo);
        $this->display();
    }
    //保存用户的资料
    public function usereditsave(){

            $userModel=M('user');
            $agentId=$_SESSION['agent']['id'];
            $data['Username']=I("post.userName");
            if(!$data['Username']) $this->error("请选择要修改的用户");
            $condition['ProxyId']=$agentId;
            $condition['Username']=$data['Username'];
            $userInfo=$userModel->where($condition)->find();
            if(!$userInfo)  $this->error("用户不存在");
            $data['Id']=$userInfo['Id'];
            $data['Realname']=I("post.realName");
            $data['Company']=I("post.company");
            $data['Mobile']=I("post.mobile");
            $data['QQ']=I("post.qq");
            $data['Email']=I("post.email");
            $resutlt=$userModel->save($data);
           if($resutlt==0){
               $ajax['status']='false';
               $ajax['Msg']='资料未修改';
               echo json_encode($ajax);
               die();
           }else if($resutlt !== false){
               $ajax['status']='true';
               $ajax['Msg']="修改成功";
               echo json_encode($ajax);
               die();
           }else{
               $ajax['status']='false';
               $ajax['Msg']="修改失败";
               echo json_encode($ajax);
               die();
           }
    }

    //暂停客户
    public  function pauseuser(){

        $userId=I("post.userId");
        $agentId=$_SESSION['agent']['id'];
        $condition['ProxyId']=$agentId;
        $condition['Id']=$userId;
        $userInfo=M('user')->where($condition)->find();
        if(!$userInfo){
            $ajax['status']="false";
            $ajax['Msg']="用户不存在";
            echo json_encode($ajax);
            die();
        }
        $userName=$userInfo['Username'];

        //暂停用户
        $result=M('user')->where("Id=$userId")->setField("Active",0);
        //暂停用户下的站点
       M('website')->where("Userid=$userId")->setField("Status",0);
        //暂停用户下的关键词
        M('keyword')->where("Username='".$userName."'")->setField("Status",0);
        if($result){
            $ajax['status']="true";
            $ajax['Msg']="暂停成功";
            echo json_encode($ajax);
            die();
        }else{
            $ajax['status']="false";
            $ajax['Msg']="暂停失败";
            echo json_encode($ajax);
            die();
        }
    }

    //开启客户
    public function startuser(){

        $userId=I("post.userId");
        $agentId=$_SESSION['agent']['id'];
        $condition['ProxyId']=$agentId;
        $condition['Id']=$userId;
        $userInfo=M('user')->where($condition)->find();
            if(!$userInfo){
                $ajax['status']="false";
                $ajax['Msg']="用户不存在";
                echo json_encode($ajax);
                die();
            }
        $userName=$userInfo['Username'];

        //开启用户
        $result=M('user')->where("Id=$userId")->setField("Active",1);
        //开启用户下的站点
        M('website')->where("Userid=$userId")->setField("Status",1);
        //开启用户下的关键词
        M('keyword')->where("Username='".$userName."'")->setField("Status",1);
        if($result){
            $ajax['status']="true";
            $ajax['Msg']="开启成功";
            echo json_encode($ajax);
            die();
        }else{
            $ajax['status']="false";
            $ajax['Msg']="开启失败";
            echo json_encode($ajax);
            die();
        }
    }

    //删除客户
    public function userdel()
    {
        $userid = I("post.userId");
        $agentId = $_SESSION['agent']['id'];
        $condition['ProxyId']=$agentId;
        $condition['Id']=$userid;
        $user=M('user')->where($condition)->find();

        if(!$user){
            $ajax['status']="false";
            $ajax['Msg']="用户不存在";
            echo json_encode($ajax);
            die();
        }
        $result=M('website')->where("Userid=$userid")->select();
        if($result){
            $ajax['status']="false";
            $ajax['Msg']="请先删除用户下的站点";
            echo json_encode($ajax);
            die();
        }
        $res=M('user')->where("Id=$userid")->delete();
        if($res){
            $ajax['status']="true";
            $ajax['Msg']="删除成功";
            echo json_encode($ajax);
            die();
        }else{
            $ajax['status']="false";
            $ajax['Msg']="删除失败";
            echo json_encode($ajax);
            die();
        }
    }
//指定客户的精准词
public function jingzhunci(){

    Load("extend");
    import("ORG.Util.Page");
    $userId=I("get.userId");
    $agentId=$_SESSION['agent']['id'];
    $condition['Id']=$userId;
    $condition['ProxyId']=$agentId;
    $user=M('user')->where($condition)->find();
    if(!$user) $this->error("用户不存在");
    $this->assign("userInfo",$user);
    $username=$user['Username'];

    $sql="SELECT count(id) num , engine from yst_jingzhunrank where username='".$username."'GROUP BY engine";
    $numlist=M('jingzhunrank')->query($sql);
    $this->assign("numlist",$numlist);

    $sql="SELECT count(id) num  from yst_jingzhunrank where username='".$username."'";
    $totalnum=M('jingzhunrank')->query($sql);
    $totalnum=$totalnum[0]['num'];
    $this->assign("totalnum",$totalnum);

    $pagenumber=10;
    $list =M('jingzhunrank')->where("username='".$username."'")->page($_GET['p'])->limit($pagenumber)->order('id desc')->select();
    $this->assign("list", $list);

    $page = new Page($totalnum, $pagenumber);
    $page->setConfig("prev", "上一页");
    $page->setConfig("next", "下一页");
    $page->setConfig("first", "首页");
    $page->setConfig("last", "末页");
    $page->setConfig("theme","<span class=pageinfo> <u></u>当前 %nowPage%/%totalPage%页</span>
                                     %first% %upPage%   %linkPage%  %downPage% %end%");
    $pageshow = $page->show();
    $this->assign("pageshow", $pageshow);
    $this->display();
}
//给新添加的用户添加站点和关键词
 public function addsitekeyword(){

     //1.添加站点
     if($_POST){
         $siteModel = D("website");
         $domain=I("post.domain");
         $condition['Domain']=$domain;
         $result=$siteModel->where($condition)->find();
         if($result){
             $ajax['status']="false";
             $ajax['Msg']="站点已存在";
             $ajax=json_encode($ajax);
             echo $ajax;
             die();
         }
         unset($result);
         $data['Webname']=I("post.Webname");
         $userName=I("post.uname");
         $data['Username']=$userName;
         $userId=M('user')->where("Username='".$data['Username']."'")->getField("Id");
         $data['Userid']=$userId;
         $data['Domain']=$domain;
         $data['Regdate']=date('Y-m-d H:i:s');
         $data['Status']=1;
         $result=$siteModel->add($data);
         unset($data);
         //2.添加关键词
         $agentId=$_SESSION['agent']['id'];
         $agentInfo=M("proxy")->find($agentId);
         $arr['keywords'] = I('post.keywords');
         $arr['moneys'] = I('post.moneys');

         $websiteId=$siteModel->where("Domain='".$domain."'")->field("Id")->find();
         $websiteId=$websiteId['Id'];
         $yqArr = M('proxyengine')->where("proxyid='".$agentId."'")->select();
         $i = 0;
         while ($i<count($arr['keywords'])){

             $data['Websiteid'] = $websiteId;
             $data['Keyword'] = $arr['keywords'][$i];

             $rs = M('keyword')->where($data)->find();

             if(!$rs){
                 $price = $arr['moneys'][$i];
                 $data['Websiteid'] = $websiteId;
                 $data['Username'] = $userName;
                 $data['Userid']=$userId;
                 $data['Website'] = $domain;
                 $data['Addtime'] = date('Y-m-d H:i:s');
                 $data['Status'] = ON;
                 $data['PageoneRate'] = $agentInfo['pageonerate'];
                 $data['PagetwoRate'] = $agentInfo['pagetworate'];
                 $data['PagethreeRate'] = $agentInfo['pagethreerate'];
                 $data['pagenumber'] = $agentInfo['pagenumber'];

                 foreach ($yqArr as $v) {
                     $data['enyinqing'] = $v['enyinqing'];
                     $data['yinqing'] = $v['yinqing'];
                     $data['Price'] = $price*$v['bili']/100;
                     $data['proxyid'] = $agentId;
                     $result = M('keyword')->add($data);
                 }
             }
             $i++;
         }
         if($result){
             $userType=M('user')->where("Username='".$data['Username']."'")->getField("Usertype");
             if($userType==1){
                 $ajax['status']="true";
                 $ajax['next']="three";
                 echo json_encode($ajax);
                 die();
             }
             if($userType==0){
                 $ajax['status']="true";
                 $ajax['Msg']="提交成功";
                 $ajax['url']="/User/userlist";
                 echo json_encode($ajax);
                 die();
             }
         }
     }
     }

    //添加精准词
 public function addjingzhun(){

  $jingzhunci=I("post.jingzhunci");
  $userName=I("post.name");
  $B2B=I("post.b2b");
  $Dis=I("post.district");

  $userMoney= M("user")->where("Username='".$userName."'")->getField("Usermoney");
  $userType=  M("user")->where("Username='".$userName."'")->getField("Usertype");
     if($userType==0){
         if($userMoney<2000){
             $ajax['status']="false";
             $ajax['Msg']="转为精准词客户需扣费2000，用户余额不足";
             echo json_encode($ajax);
             die();
         }else{
             M("user")->where("Username='".$userName."'")->setField("Usertype",1);
             M("user")->where("Username='".$userName."'")->setDec("Usermoney",2000);
         }
     }
  $jingzhunci=explode(",",$jingzhunci);
  $houZhui="";
   foreach($jingzhunci as $k=>$v){
       if($v<10000){
           unset($jingzhunci[$k]);
           continue;
       }
      $jingzhunci[$k]=$v-10000;
       $houZhui.=$jingzhunci[$k].",";
   }
   $houZhui=substr($houZhui,0,-1);

     $Dis=explode(",",$Dis);
     $District="";
     foreach($Dis as $k=>$v){
         $District.=$Dis[$k].",";
     }
     $District=substr($District,0,-1);

   M("user")->where("Username='".$userName."'")->setField("Houzhui",$houZhui);
   M("user")->where("Username='".$userName."'")->setField("B2bstr",$B2B);
   M("user")->where("Username='".$userName."'")->setField("District",$District);
     $ajax['status']="true";
     $ajax['Msg']="提交成功";
     $ajax['url']="/User/userlist";
     echo json_encode($ajax);
     die();
 }
    /**
     * 生成推荐词的JSON数据格式
     */
    public  function  getjson()
    {
        $json = "";
        $mode = new Model();
        $agentId =$_SESSION['agent']['id'];
        $sql = "SELECT h.id,h.name,ht.id as tid,ht.name as tname ";
        $sql .= " from yst_houzhui h,yst_houzhuitype ht where h.type=ht.id and h.proxyid in('0','".$agentId."') order by ht.id asc";
        $data = $mode->query($sql);

        $houzhuitype = M("houzhuitype");
        $map['proxyid'] = array('in',"0,$agentId");
        $htdata = $houzhuitype->where($map)->order("id desc")->select();

        $template='{"id":"%d","pId":"%d","name":"%s","open":"%s"},';
        $template1='{"id":"%d","pId":"%d","name":"%s"},';
        $htkeydata = array();
        foreach ($htdata as $k => $v)
        {
            $json .= sprintf($template, $v["id"], 0,$v["name"],"true");
            $htkeydata[$v["id"]] = $v;
        }
        //------------------------------------------后缀词类型
        foreach ($data as $k1 => $v1)
        {
            $json .= sprintf($template1, "10000" + $v1["id"],  $v1["tid"],$v1["name"]);
        }
        $json = substr($json, 0, -1);
        return $json;
    }

    public  function  diqudata()
    {
        $selectedvalue = ""; //被选中值列表
        $showstr = "";
        $area = M("areas");
        $condition["area_type"] = array("exp", "in(0,1,2) ");
        $data = $area->where($condition)->select();
        $jscontent = "";
        $temp1='{"id":"%d","pId":"%d","name":"%s","open":"%s"},';
        $temp='{"id":"%d","pId":"%d","name":"%s"},';
        foreach ($data as $onerow) {
            $rowid=$onerow["area_id"];
            $selected="";
            if(strpos($selectedvalue,$rowid)!==false)
                $selected=", checked:true";

            if ($onerow["area_type"] == "0")
                $jscontent = $jscontent . sprintf($temp1,$rowid, $onerow["parent_id"], $onerow["area_name"],"true");
            else
                $jscontent = $jscontent . sprintf($temp,$rowid, $onerow["parent_id"], $onerow["area_name"]);

        }
        $jscontent = substr($jscontent, 0, -1);
        $showstr = $jscontent;
        return $showstr;
    }
    //某一用户某一天的消费
    public function userdayxf(){

         $userId=I("get.userId");
         $agentId=$_SESSION['agent']['id'];
         $userModel=M("user");
         $condition['Id']=$userId;
        $condition['ProxyId']=$agentId;
        $result=$userModel->where($condition)->find();
        if(!$result) $this->error("用户不存在");
        $userName=$result['Username'];
        $days=I("get.days");
        $consumptionModel=M("consumption");
        $sql="select * from yst_consumption where username='".$userName."' and to_days(addtime)=$days";
        $list=$consumptionModel->query($sql);
        $this->assign("list",$list);
        $this->display();
    }

    //主词客户转为精准词客户
    public function tojingzhunci(){

        $agentId=$_SESSION['agent']['id'];
        $userId=I("get.userId");
        $userModel=M("user");
        $condition['ProxyId']=$agentId;
        $condition['Id']=$userId;
        $result=$userModel->where($condition)->find();
        if(!$result){
            $this->error("用户不存在");
        }
        $userName=$result['Username'];
        $this->userName=$userName;
        $hzstr = $this->getjson();
        $this->houzhui = $hzstr; //---------------------后缀词类型数据 json
        $diqustr = $this->diqudata();
        $this->diqustr = $diqustr;//--------------------地区数据  json

        $this->display();
    }
    //某个代理商在今年某月增加的客户数量列表
    public function useraddmonthly(){

        $agentId=$_SESSION['agent']['id'];
        $month=I("get.month");
        $month=(int)$month;
        $sql="select * from yst_user where ProxyId=$agentId and DATE_FORMAT(Regtime,'%m')=$month and  DATE_FORMAT(Regtime,'%Y')= DATE_FORMAT(CURDATE(),'%Y')";
        $user=M("user");
        $list=$user->query($sql);
        $this->assign("list",$list);
        $this->month=$month;
        $this->display();
    }
    //修改用户的密码
    public function userpassword(){
        $userId=I("get.userId");
        $agentId=$_SESSION['agent']['id'];
        $condition['Id']=$userId;
        $condition['ProxyId']=$agentId;
        $user=M("user");
        $result=$user->where($condition)->find();
        if(!$result){$this->error("用户不存在！");}
        $this->assign("userId",$userId);
        $this->display();
    }

    //保存用户修改的密码
    public function userpasswordsave(){

       $agentId=$_SESSION['agent']['id'];
       $id=I("post.userId");
       $condition['ProxyId']=$agentId;
       $condition['Id']=$id;
        $user=M("user");
        $result=$user->where($condition)->find();
        if(!$result){$this->error("用户不存在！");}
        $oldpass=I("post.oldpass");
        $oldpass=md5($oldpass);
        if($oldpass!=$result['Password']){
            $ajax["status"]="false";
            $ajax["Msg"]="原密码输入不正确";
            echo json_encode($ajax);
            die();
        }
        $password=I("post.password");
        $twopass=I("post.twopass");
        if($password!=$twopass){
            $ajax["status"]="false";
            $ajax["Msg"]="两次输入的新密码不一致";
            echo json_encode($ajax);
            die();
        }
       $password=md5($password);
       $res=$user->where($condition)->setField("Password",$password);
        if($res == 0 ){
            $ajax["status"]="false";
            $ajax["Msg"]="密码未修改";
            echo json_encode($ajax);
            die();
        }else if($res !== false){
            $ajax["status"]="true";
            $ajax["Msg"]="密码修改成功";
            echo json_encode($ajax);
            die();
        }else{
            $ajax["status"]="false";
            $ajax["Msg"]="密码修改失败";
            echo json_encode($ajax);
            die();
        }
    }
}
?>